package com.jml.集群;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class Consumer {

    /**
     * 获取我们的消息
     */
    public void consumer() throws MQClientException {
        // 获取消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer();
        consumer.setNamesrvAddr("192.168.212.169:9876");
        consumer.setConsumerGroup("mayiktConsumer");
        consumer.subscribe("mtTopic", "");
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.registerMessageListener(new MessageListenerOrderly() {
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                context.setAutoCommit(true);
                for (MessageExt ext : msgs) {
                    System.out.println("消费者获取消息,队列id：" + ext.getQueueId() + "," +
                            new String(ext.getBody()) + "msgid:" + ext.getMsgId());
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        consumer.start();


    }

    public static void main(String[] args) throws MQClientException {
        new Consumer().consumer();
    }
}

